import { Canvas, CanvasProps } from "@react-three/fiber";
import { FC, ReactNode, useEffect, useState } from "react";

// We need this because of safari and the fact that webkit has a bug that doesnt like odd viewport numbers
// when computing 3D matrices.

type Props = {
  children: ReactNode;
  canvasProps?: CanvasProps;
};

const even = (n: number) => Math.floor(n) & ~1; // integer → even

const CanvasWrapper: FC<Props> = ({ children, canvasProps = {} }) => {
  const [size, setSize] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const clampSize = () =>
      setSize({
        width: even(window.innerWidth),
        height: even(window.innerHeight),
      });

    clampSize(); // run once on mount
    window.addEventListener("resize", clampSize);
    window.visualViewport?.addEventListener("resize", clampSize);

    return () => {
      window.removeEventListener("resize", clampSize);
      window.visualViewport?.removeEventListener("resize", clampSize);
    };
  }, []);

  return (
    <div
      style={{
        width: "100vw",
        height: "100dvh",
        overflow: "hidden",
      }}
    >
      <Canvas style={{ width: size.width, height: size.height }} {...canvasProps}>
        {children}
      </Canvas>
    </div>
  );
};

export { CanvasWrapper };
